package zqservlet;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import zqdb.O_INFO;
import zqtools.DBUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

@WebServlet(name = "gzServlet", urlPatterns = "/gz")
public class gzServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StringBuilder sbr = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sbr.append(line).append('\n');
            }
            if (sbr.length() > 1) {
                sbr.replace(sbr.length() - 1, sbr.length(), "");
            }
        } catch (IOException e) {
            System.out.println(("RequestUtil,IOException:" + e));
        }
        String str = sbr.toString();

        String key1 = cotants.key1;
        O_INFO of = new O_INFO();
        String ls_geSign = "";
        StringBuilder sb = new StringBuilder();
        Map<Object, Object> data = jsonToMap(str);
        Set<Object> set = data.keySet();
        Object[] arr = set.toArray();
        Arrays.sort(arr);
        for (Object key : arr) {
            if (data.get(key).toString().trim().length() > 0) {
                if (key.equals("sign")) {
                    ls_geSign = data.get(key).toString().trim();
                } else if (key.equals("menu")) {
                    continue;
                }
                if ("code".equals(key)) {
                    of.setVALUE01(data.get(key).toString().trim());
                } else if ("order_no".equals(key)) {
                    of.setVALUE02(data.get(key).toString().trim());
                } else if ("order_type".equals(key)) {
                    of.setVALUE03(data.get(key).toString().trim());
                } else if ("pay_type".equals(key)) {
                    of.setVALUE04(data.get(key).toString().trim());
                } else if ("client_no".equals(key)) {
                    of.setVALUE05(data.get(key).toString().trim());
                } else if ("date_time".equals(key)) {
                    of.setVALUE06(data.get(key).toString().trim());
                } else if ("money".equals(key)) {
                    of.setVALUE07(data.get(key).toString().trim());
                } else if ("place_type".equals(key)) {
                    of.setVALUE08(data.get(key).toString().trim());
                }
                sb.append(key).append("=").append(data.get(key).toString().trim()).append("&");
            }
        }
        sb.append("key=").append(key1);

        com.alibaba.fastjson.JSONObject jRet = new com.alibaba.fastjson.JSONObject();
        com.alibaba.fastjson.JSONObject jRetSub = new com.alibaba.fastjson.JSONObject();

        if (ls_geSign.isEmpty()) {
            jRet.put("code", "200");
            jRet.put("sub_code", "FAIL");
            jRet.put("msg", "没有签名信息");
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print(jRet);
            jRet.clear();
            return;
        }

        String ls_sign = null;
        try {
            ls_sign = f_MD5(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        assert ls_sign != null;
        if (ls_sign.equals(ls_geSign)) {
            jRet.put("code", "200");
            jRet.put("sub_code", "FAIL");
            jRet.put("msg", "无效签名信息");
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print(jRet);
            jRet.clear();
            return;
        }

        JSONObject jDb = DBUtil.f_queryGz(of);
        JSONObject jval = jDb.getJSONArray("db1").getJSONObject(0);
        if ("ZZ01".equals(jval.get("VALUE01"))) {
            jRet.put("code", "200");
            jRet.put("sub_code", "FAIL");
            jRet.put("msg", jval.get("VALUE02"));
            jRet.put("data", jRetSub);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print(jRet);
            jRet.clear();
            return;
        }

        jRet.put("code_status", 200);
        jRet.put("code_sub", "SUCCESS");
        jRet.put("msg", "交易成功");
        JSONArray jarr = new JSONArray();
        jRetSub.put("code", jval.get("VALUE03"));
        jRetSub.put("money", jval.get("VALUE05"));
        jRetSub.put("balance", jval.get("VALUE04"));
        jRetSub.put("user_name", jval.get("VALUE02"));
        jRetSub.put("pay_type", jval.get("VALUE06"));
        jRetSub.put("order_no", jval.get("VALUE07"));
        jarr.add(jRetSub);
        jRet.put("data", jarr);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(jRet);
        jRet.clear();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    public static Map<Object, Object> jsonToMap(Object jsonObj) {
        JSONObject jsonObject = JSONObject.fromObject(jsonObj);
        return (Map<Object, Object>) (Map) jsonObject;
    }

    public static String f_MD5(String data) throws Exception {
        java.security.MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
        }
        return sb.toString();
    }

}
